﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace GetNewsService
{
    partial class GetNews : ServiceBase
    {
        public GetNews()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。           
            this.timer2.Interval = 4*3600*1000;//10000D;

            writeLog(" GetNews Seivice Start.");
            writeLog("timer1 timer:" + timer2.Interval.ToString());

            this.timer2.Start();
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            this.timer2.Stop();
            this.timer2.Dispose();
        }
        

        private void timer2_Elapsed(object sender, EventArgs e)
        {
            writeLog(" timer1 Start.");
            try
            {
                GetNewsMain getNewMain = new GetNewsMain();

                //删除3天以前的新闻
                getNewMain.Delete();

                List<RssModel> rssList = getNewMain.GetRssList();
                List<NewsModel> allNews = new List<NewsModel>();
                List<NewsModel> rssNews = null;
                foreach (RssModel o in rssList)
                {
                    rssNews = getNewMain.GetNewsList(o);
                    if (rssNews != null && rssNews.Count > 0)
                    {
                        allNews.AddRange(rssNews);
                    }
                }

                List<NewsModel> sourceNews = getNewMain.GetALLNews();

                //移除重复的新闻
                allNews.RemoveAll(delegate(NewsModel o)
                {
                    if (sourceNews.Exists(delegate(NewsModel n)
                    {
                        if (n.NewsUrl.ToLower().Trim().Equals(o.NewsUrl.ToLower().Trim()))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });

                if (allNews.Count > 0)
                {
                    getNewMain.InsertNews(allNews);

                }
            }
            catch (Exception ex)
            {
                writeLog(ex.Message);
                OnStop();
            }
        }
        

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        private void writeLog(string content)
        {
            try
            {
                //获取服务相对路径          
                string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;
                string fullPath = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();
                fullPath = fullPath.Replace("\"", string.Empty);//替换掉双引号  
                FileInfo fi = new FileInfo(fullPath);
                string path = fi.Directory.ToString() + "\\Log";
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);
                path += "\\log_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".txt";
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + " " + content);
                }
            }
            catch (Exception ex)
            {
                writeLog(ex.Message);
                OnStop();
            }
        }
    }
}
